import random as rd
import sys
from copy import copy
from datetime import date

from tqdm import tqdm

from enigma import CHARS


def generate_random_state(num_wheels):
    all_states = []
    for _ in range(num_wheels):
        all_states.append(chr(rd.sample(CHARS, 1)[0]))
    return ''.join(all_states)

def generate_random_singletable():
    chars = copy(CHARS)
    rd.shuffle(chars)
    odd = []
    double = []
    n = 0
    for c in chars:
        if n % 2 == 0:
            double.append(c)
        else:
            odd.append(c)
        n += 1
    output = list(zip(odd, double))
    result = []
    for i in output:
        result.append(f'{chr(i[0])}{chr(i[1])}')
    return ' '.join(result)

def generate_random_wheel_num(num_wheels):
    l = list(range(1,9))
    rd.shuffle(l)
    return ''.join(list(map(str,l[:num_wheels])))

def generate_codebook(num_wheels: int, start_timestamp: int, end_timestamp: int):
    codebook = []
    for t in tqdm(range(start_timestamp, end_timestamp, 86400)):
        d = date.fromtimestamp(t)
        codebook.append(
            f'{d.strftime("%Y%m%d")},'
            f'{generate_random_wheel_num(num_wheels)},'
            f'{generate_random_state(num_wheels)},'
            f'{generate_random_state(num_wheels)},'
            f'{generate_random_singletable()}\n'
        )

    return codebook


if __name__ == '__main__':
    NUM_WHEELS = int(sys.argv[1])
    with open(f'codebook_{NUM_WHEELS}.csv', 'w') as fo:
        fo.write('date,wheel_num,carry_state,init_state,single_table\n')
        cobdebook = generate_codebook(NUM_WHEELS, 0, 6400000000)
        fo.writelines(cobdebook)